<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm">
      <template #addr="{ model, field }">
        <RegionCascader
          v-model="model[field]"
          :region-key-enum="{
            0: 'province',
            1: 'city',
            2: 'county',
            3: 'townShip',
          }"
          @checked-details="handleCascaderData"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { BizConfigTypeEnum } from '@/enums/systemEnum';
  import { RegionCascader } from '@/components/RegionCascader';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { modalFormSchema, selfPickupAddrFormSchema } from './data';

  const { SystemModule } = mcApi;
  const { BizConfigApi } = SystemModule;

  const [registerForm, { setFieldsValue, resetFields, validate, resetSchema }] = useForm({
    labelWidth: 150,
    schemas: modalFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({
      minHeight: 50,
      title: '业务配置',
      confirmLoading: false,
    });
    const dataSource = data?.dataSource || {};
    const { type, extDetailsInfo } = dataSource;
    const ifSelfPickupAddr: boolean = type === BizConfigTypeEnum.SELF_PICKUP_ADDR;
    await resetSchema(ifSelfPickupAddr ? selfPickupAddrFormSchema : modalFormSchema);
    // 自提地址
    if (ifSelfPickupAddr) {
      const { details, provinceId, cityId, countyId, townShipId } = extDetailsInfo || {};
      dataSource.details = details;
      addrData.value = extDetailsInfo;
      dataSource.addr = [provinceId, cityId, countyId, townShipId];
    }
    await setFieldsValue(dataSource);
  });

  const addrData = ref<any>({});
  function handleCascaderData(data: any) {
    addrData.value = data || {};
  }

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      const values: any = await validate();
      setModalProps({ confirmLoading: true });
      const model = {
        ...values,
        addr: undefined,
        details: undefined,
        extDetailsInfo: {
          ...addrData.value,
          details: values.details,
        },
      };
      await BizConfigApi.saveBizConfig(model);
      createMessage.success(`操作成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less">
  :deep(.ant-select-selector) {
    color: #000000e0 !important;
  }
</style>
